package beanAction;


import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;

import modele.beanEntity.User;
import modele.mapper.UserMapper;

@ManagedBean(name="registerbean")
@RequestScoped
public class RegisterBean {
	private User user;
	private UIComponent uiComponent;
	
	public RegisterBean(){
		user=new User();
	}
	
	public void attrListener(ActionEvent e){
		uiComponent= e.getComponent();
	}
	
	public void register(){
		if(user != null && user.getLogin() != null && user.getPassword() != null ){
			
			try {
				UserMapper um = new UserMapper();
				if(!um.loginExists(user.getLogin())){
					if(um.createUser(user) == true){
						FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Utilisateur "+this.user.getLogin()+" enregistré avec succès",null));
						this.reset();
					}else{
						FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Echec de l'enregistrement",null));
					}
				}else{
					FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Le login renseigné existe déjà",null));
				}
			} catch (Exception e) {
				FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR,"Erreur interne",null));
			}
			
		}
	}
	
	public void reset(){
		this.user=new User();
		this.uiComponent=null;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	
}
